
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'

// 导出excel--链接形式
export async function exportList(api,name='文件')  {
	const content = api
	const blob = new Blob([content], { type: 'application/vnd.ms-excel' })
	const fileName = name + '.xlsx'
	if ('download' in document.createElement('a')) { // 非IE下载
		const elink = document.createElement('a')
		elink.download = fileName
		elink.style.display = 'none'
		elink.href = URL.createObjectURL(blob)
		document.body.appendChild(elink)
		elink.click()
		URL.revokeObjectURL(elink.href) // 释放URL 对象
		document.body.removeChild(elink)
	} else { // IE10+下载
		navigator.msSaveBlob(blob, fileName)
	}
}

// 导出excel 表格形式
export async function exportTable(ID='table',name='未知文件'){
	var xlsxParam = { raw: true } //转换成excel时，使用原始的格式
	/* 从表生成工作簿对象 */
	var wb = XLSX.utils.table_to_book(
		document.querySelector('#'+ID),
		xlsxParam
	)
	/* 获取二进制字符串作为输出 */
	var wbout = XLSX.write(wb, {
		bookType: 'xlsx',
		bookSST: false,
		type: 'array'
	})
	try {
		await FileSaver.saveAs(
			new Blob([wbout], {
				type: 'application/octet-stream'
			}),
			//设置导出文件名称
			name + '.xlsx'
		)
	} catch (e) {
		if (typeof console !== 'undefined') console.log(e, wbout)
	}
	return wbout
}

/**
 * 下载文件
 * @param  {String} url 目标文件地址
 * @param  {String} filename 想要保存的文件名称
 */
export function courseDownload(url, filename) {
	getBlob(url, function (blob) {
		saveAs(blob, filename);
	})
}

export function saveAs(blob, filename) {
	if (window.navigator.msSaveOrOpenBlob) {
		navigator.msSaveBlob(blob, filename);
	} else {
		var link = document.createElement('a');
		var body = document.querySelector('body');

		link.href = window.URL.createObjectURL(blob);
		link.download = filename;

		// fix Firefox
		link.style.display = 'none';
		body.appendChild(link);

		link.click();
		body.removeChild(link);

		window.URL.revokeObjectURL(link.href);
	}
}

export function getBlob(url, cb) {
	var xhr = new XMLHttpRequest();
	xhr.open('GET', url, true);
	xhr.responseType = 'blob';
	xhr.onload = function () {
		if (xhr.status === 200) {
			cb(xhr.response);
		}
	};
	xhr.send();
}